﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ESRI.ArcGIS.Carto;
using ESRI.ArcGIS.Geodatabase;
using ESRI.ArcGIS.Controls;

namespace MyMap
{
    class MyMxdDocClass
    {

        private IMapDocument mapDocument = new MapDocumentClass();

        // 新建地图文档
        public void newMapDoc(AxMapControl axMapControl)
        {
            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.Title = "新建地图文档";
            saveFileDialog.Filter = "Mxd文档（*.mxd）|*.mxd";
            DialogResult dialogResult = saveFileDialog.ShowDialog();

            if (dialogResult != DialogResult.OK)
            {
                return;
            }

            mapDocument.New(saveFileDialog.FileName);
            mapDocument.Open(saveFileDialog.FileName);
            axMapControl.Map = mapDocument.get_Map(0);
        }

        // 打开地图文档
        public void openMapDoc(AxMapControl axMapControl)
        {
            // 打开地图文档对话框
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Title = "打开地图文档";
            openFileDialog.Filter = "Mxd文档（*.mxd）|*.mxd";
            DialogResult dialogResult = openFileDialog.ShowDialog();

            if (dialogResult != DialogResult.OK)
            {
                return;
            }

            // 打开地图文档，并加载到MapControl控件
            if (mapDocument.get_IsMapDocument(openFileDialog.FileName))
            {
                // 打开地图文档
                mapDocument.Open(openFileDialog.FileName);
                for (int i = 0; i < mapDocument.MapCount; i++)
                {
                    axMapControl.Map = mapDocument.get_Map(i);
                }
                axMapControl.ActiveView.Refresh();
            }
        }

        // 保存地图文档
        public void saveMapDoc(AxMapControl axMapControl)
        {

            if (mapDocument.get_IsReadOnly(mapDocument.DocumentFilename))
            {
                MessageBox.Show("地图文档只读！");
                return;
            }

            mapDocument.Save();
            MessageBox.Show("保存成功！");
        }

        // 地图文档另存为
        public void SaveAsMapDoc(AxMapControl axMapControl)
        {
            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.Title = "地图文档另存为";
            saveFileDialog.Filter = "Mxd文档（*.mxd）|*.mxd";
            DialogResult dialogResult = saveFileDialog.ShowDialog();

            if (dialogResult != DialogResult.OK)
            {
                return;
            }

            if (mapDocument.get_IsReadOnly(mapDocument.DocumentFilename))
            {
                MessageBox.Show("地图文档只读！");
                return;
            }

            mapDocument.SaveAs(saveFileDialog.FileName);
            mapDocument.Open(saveFileDialog.FileName);
            MessageBox.Show("保存成功！");
        }
    }
}
